<?php
namespace app\admin\controller;

use think\Db;
use think\facade\Cache;

class Runtime extends Base
{
	public function runtime()
	{
        if ($this->request->isPost() && $this->request->isAjax()) {
            $runtime = [];

            $cache_folder = glob(Env('runtime_path') . 'cache/*');
            $cache_count = 0;
            foreach ($cache_folder as $folder) {
                $cache_count += count(glob($folder . '/*.php'));
            }
            $runtime[] = [
                'id'    => 'cache',
                'name'  => '系统缓存',
                'count' => $cache_count,
                'ope'   => '更新'
            ];

            $temp = glob(Env('runtime_path') . 'temp/*.php');
            $runtime[] = [
                'id'    => 'temp',
                'name'  => '模板缓存',
                'count' => count($temp),
                'ope'   => '清空'
            ];

            $log_folder = glob(Env('runtime_path') . 'log/*');
            $log_count = 0;
            foreach ($log_folder as $folder) {
                $log_count += count(glob($folder . '/*.log'));
            }
            $runtime[] = [
                'id'    => 'log',
                'name'  => '系统日志',
                'count' => $log_count,
                'ope'   => '清空'
            ];

            // 返回数据
            $data = [
                'code'  => 0,
                'msg'   => '',
                'count' => count($runtime),
                'data'  => $runtime,
            ];

            return json($data);
        }

		return $this->fetch();
	}

    public function runtimeClear()
    {
        if ($this->request->isPost() && $this->request->isAjax()) {
            $id = $this->request->param('id/s', '');

            if ('cache' === $id) {
                // $log_folder = glob(Env('runtime_path') . 'cache/*');
                // foreach ($log_folder as $folder) {
                //     array_map('unlink', glob($folder . '/*.php'));
                //     rmdir($folder);
                // }
                $msg = '';
                $msg .= Cache::set('site', Db::table('site')->find(1) ?: []) ? '网站设置缓存更新成功<br>' : '网站设置缓存更新失败<br>';
                $msg .= Cache::set('column', Db::table('column')->column('*', 'id')) ? '栏目缓存更新成功<br>' : '栏目缓存更新失败<br>';
                $msg .= Cache::set('block', Db::table('block')->column('content', 'id')) ? '区块缓存更新成功<br>' : '区块缓存更新失败<br>';

                $this->result('', 1, $msg);
            } elseif ('temp' === $id) {
                array_map('unlink', glob(Env('runtime_path') . 'temp/*.php'));
            } elseif ('log' === $id) {
                $log_folder = glob(Env('runtime_path') . 'log/*');
                foreach ($log_folder as $folder) {
                    array_map('unlink', glob($folder . '/*.log'));
                    rmdir($folder);
                }
            } else {
                $this->result('', 1, '参数错误');
            }

            $this->result('', 0, '清除完成');
        }
    }
}
